import { ActionBase } from "../../ActionBase";

/**
 * 放置site Action
 */
export class ActionPlaceSite  extends ActionBase<IActionCMD<"placePlan">>
{
    public execute(action: IActionCMD<"placePlan">): ActionCode 
    {
        const room = Game.rooms[action.arg.task.data.arg.roomName];
        if(!room  )
        {
            return 0;
        }
        const sitecache = room.getWorld().PollConstructSites(room.name);
        if(sitecache && sitecache.cacheData.length>5)
        {
            return 0;
        }
        const plans = action.arg.task.data.arg.plan;
        let i=20;
        while(plans.length>0&& i>0)
        {
            i--;
            const planitem = plans[0] as IPlanItem;
            const findstructure =  room.lookForAt(LOOK_STRUCTURES,planitem.pos.x,planitem.pos.y);
            if(findstructure.findIndex(item=>item.structureType   == planitem.type)>=0)
            {
                // 存在要放置的建筑
                plans.splice(0,1);
            }
            else if(room.lookForAt(LOOK_CONSTRUCTION_SITES,planitem.pos.x,planitem.pos.y).findIndex(e=>e.structureType == planitem.type)>=0)
            {
                // 存在要放置的site
                plans.splice(0,1);
            }
            else
            {
                 
                // 摧毁不要的建筑
                if(planitem.type!=STRUCTURE_ROAD &&  findstructure.length>0)
                {
                    for(const item of findstructure)
                    {
                        if(item.structureType == STRUCTURE_CONTAINER || 
                            item.structureType == STRUCTURE_ROAD||
                            (item.structureType == STRUCTURE_RAMPART && (item as OwnedStructure).my))
                        {
                            // 这个建筑是container跳过
                            continue;
                        }
                        item.destroy();
                    }
                }
                const code =  room.createConstructionSite(planitem.pos.x,planitem.pos.y,planitem.type);
                // 不堵住了，按照顺序来
                if(code === OK)
                {
                    plans.splice(0,1);
                    break;// 每tick只放一个
                }
                else
                {
                    // global.Log.Warning(`建造错误:${code} ${JSON.stringify(planitem)}`);
                    if(code == ERR_INVALID_TARGET)
                    {
                        plans.splice(0,1);
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        return 0;
    }
}